package ink.onei.framework.web.service;

import ink.onei.common.core.domain.entity.Seller;
import ink.onei.common.core.domain.model.LoginUser;
import ink.onei.common.exception.ServiceException;
import ink.onei.common.utils.MessageUtils;
import ink.onei.common.utils.StringUtils;
import ink.onei.user.service.ISellerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 卖家验证处理
 *
 * @author nekotako
 */
@Service("sellerDetailsService")
public class SellerDetailServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(SellerDetailServiceImpl.class);

    @Autowired
    private ISellerService sellerService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Seller temp = new Seller();
        temp.setUsername(username);
        Seller seller = sellerService.getSellerDetail(temp);
        if (StringUtils.isNull(seller)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        }

        return createLoginUser(seller);
    }

    public UserDetails createLoginUser(Seller seller) {
        return new LoginUser(seller.getSellerId(), seller, permissionService.getMenuPermission(seller));
    }
}
